<template>
  <div class="global-container1">
    <div class="root">
      <el-tooltip
        class="item"
        effect="dark"
        content="放大"
        placement="bottom"
        style="cursor: pointer;"
      >
        <i class="fa fa-search-plus" :style="{'margin-left': marginLeftSize}" style="font-size: 20px;"
           @click="zoomFn(1.2)"></i>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="缩小"
        placement="bottom"
        style="cursor: pointer;"
      >
        <i class="fa fa-search-minus" style="font-size: 20px; margin-left: 15px;"
           @click="zoomFn(0.8)"></i>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="保存为图片"
        placement="bottom"
        style="cursor: pointer;"
      >
        <i class="fa fa-floppy-o" style="font-size: 20px; margin-left: 15px;" @click="dumpImage"></i>
      </el-tooltip>
      <i class="fa fa-square" aria-hidden="true" style="color: #ecf3ff; font-size: 22px; margin-left: 20px;"
         v-show="openType === 'deploy'"
      ></i>
      <span style="margin-left: 2px;"
            v-show="openType === 'deploy'"
      >
        未编排
      </span>
      <!--      #7cf838-->
      <!--      f0f9eb-->
      <i class="fa fa-square" aria-hidden="true" style="color: #e6f8dd; font-size: 22px; margin-left: 20px;"
         v-show="openType === 'deploy'"
      ></i>
      <span style="margin-left: 2px;"
            v-show="openType === 'deploy'"
      >
        已编排
      </span>
      <el-button
        type="primary" style="float:right; margin-right: 5px;" size="mini" @click="backToServiceGroup"
        v-show="openType === 'detail' || openType === 'edit' || openType === 'deploy'"
        class="el-button-primary-style"
      >
        返回
      </el-button>
      <el-button
        type="primary" style="float:right; margin-right: 5px;" size="mini" @click="backToServiceGroup"
        v-show="openType === 'create'"
        class="el-button-primary-style"
      >
        取消
      </el-button>
      <el-button
        type="primary" style="float:right; margin-right: 5px;" size="mini" @click="save"
        v-show="openType === 'create' || openType === 'edit'"
        class="el-button-primary-style"
      >
        保存
      </el-button>
      <el-button
        type="primary" style="float:right; margin-right: 5px;" size="mini" v-show="openType === 'deploy'"
        @click="deployServiceGroup"
        class="el-button-primary-style"
      >
        部署
      </el-button>
      <!-- 左侧列表 -->
      <item-panel
        ref="itemPanelList"
        :graph="graph"
        v-show="openType === 'create' || openType === 'edit'"
      />

      <!-- 挂载节点 -->
      <div
        id="canvasPanel"
        ref="canvasPanel"
        @dragover.prevent
      />

      <!--      <el-drawer-->
      <!--        title="数据配置"-->
      <!--        :visible.sync="configVisible"-->
      <!--        direction="rtl"-->
      <!--        size="60%"-->
      <!--      >-->
      <!--        :before-close="handleClose"-->
      <service-group-deploy-drawer
        ref="serviceGroupDeployDrawer"
        :app-name="selectAppName"
        :app-interface="selectAppInterface"
      ></service-group-deploy-drawer>

      <service-group-yaml-deploy-drawer
        ref="serviceGroupYamlDeployDrawer"
        :select-yaml-id="selectYamlId"
        :selectYamlAppName="selectYamlAppName"
        :selectYamlInterface="selectYamlInterface"
      ></service-group-yaml-deploy-drawer>
      <!--        <div>-->
      <!--          <h2 class="panel-title">数据配置</h2>-->
      <!--          <div class="config-data">-->
      <!--            id: {{ config.id }}, data: {{ config.data }}-->
      <!--          </div>-->
      <!--          <button @click="configVisible = false">取消</button>-->
      <!--          <button-->
      <!--            class="save"-->
      <!--            @click="save"-->
      <!--          >-->
      <!--            保存-->
      <!--          </button>-->
      <!--        </div>-->
      <!--      </el-drawer>-->

      <!-- 配置面板 -->
      <!--      <div-->
      <!--        id="configPanel"-->
      <!--        :class="{ hidden: !configVisible }"-->
      <!--      >-->
      <!--        <i-->
      <!--          class="gb-toggle-btn"-->
      <!--          @click="configVisible = !configVisible"-->
      <!--        />-->
      <!--        <h2 class="panel-title">数据配置</h2>-->
      <!--        <div class="config-data">-->
      <!--          id: {{ config.id }}, data: {{ config.data }}-->
      <!--        </div>-->
      <!--        <button @click="configVisible = false">取消</button>-->
      <!--        <button-->
      <!--          class="save"-->
      <!--          @click="save"-->
      <!--        >-->
      <!--          保存-->
      <!--        </button>-->
      <!--      </div>-->
      <div
        v-if="tooltip && !isMouseDown"
        class="g6-tooltip"
        :style="`top: ${top}px; left: ${left}px;`"
      >
        名称: {{ tooltip }}
      </div>
      <el-dialog
        title="服务组部署"
        :visible.sync="deployDialogVisible"
        width="500px"
        :destroy-on-close="true"
      >
        <div style="display: flex; justify-content: space-around">
          <div style="width: 400px;">
            <el-form
              ref="form"
              :model="gvStoreGroupDeployVo"
              label-width="120px"
            >
              <el-form-item label="服务组实例名称">
                <el-input
                  v-model="gvStoreGroupDeployVo.groupName"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <div style="display: flex; justify-content: right;">
                  <el-button type="primary" size="small" @click="startDeploy"
                             class="el-button-primary-style"
                  >
                    确 定
                  </el-button>
                  <el-button type="primary" size="small" @click="clearDialogInfo"
                             class="el-button-primary-style"
                  >
                    取 消
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import G6 from '@antv/g6'
  import registerFactory from './components/graph/graph'
  import ItemPanel from './ItemPanel.vue'
  import data from './data.js'
  import PackageListSide from '@/views/appstore/components/ServiceGroupComponents/PackageListSide.vue'
  import ServiceGroupDeployDrawer from '@/views/appstore/graph/components/ServiceGroupDeployDrawer.vue'
  import ServiceGroupYamlDeployDrawer from '@/views/appstore/graph/components/ServiceGroupYamlDeployDrawer.vue'
  import ServiceGroupDeployOneServiceDialog
    from '@/views/appstore/components/ServiceGroupDeployComponents/ServiceGroupDeployOneServiceDialog.vue'
  import {getTenantId} from '@/utils/tenantId'

  // const registerFactory = require('../../../library/welabx-g6').default;

  export default {
    components: {
      ServiceGroupDeployOneServiceDialog,
      ServiceGroupDeployDrawer,
      PackageListSide,
      ItemPanel,
      ServiceGroupYamlDeployDrawer
    },
    data() {
      return {
        mode: 'drag-shadow-node',
        graph: {},
        label: '',
        labelCfg: {
          fontSize: 12,
          style: {
            fill: '#fff'
          }
        },
        node: {
          fill: '',
          lineDash: 'none',
          borderColor: '',
          width: 160,
          height: 60,
          shape: 'rect-node'
        },
        selectAppName: '',
        selectAppInterface: '',
        selectYamlId: '',
        selectYamlAppName: '',
        selectYamlInterface: '',
        configVisible: false,
        isMouseDown: false,
        config: '',
        tooltip: '',
        top: 0,
        left: 0,
        gvStoreGroupVo: {
          appIdList: [],
          groupDescription: '',
          groupName: '',
          relationGraph: ''
        },
        openType: '',
        serviceGroupInstance: {},
        gvStoreGroupDeployVo: {
          tenantId: '',
          groupName: '',
          groupId: '',
          nodes: [],
          relationGraph: ''
        },
        nodeInfo: {
          appType: '',
          deployType: '',
          deployId: '',
          appName: '',
          appVersion: '',
          depends: [],
          useAppliedDeploy: false,
          yamlDeploy: {},
          yamlCloudDeploy: {},
        },
        deployDialogVisible: false,
        marginLeftSize: "10px",
      }
    },
    methods: {
      createGraphic(data) {
        const vm = this
        const grid = new G6.Grid()
        const menu = new G6.Menu({
          offsetX: -20,
          offsetY: -50,
          itemTypes: ['node', 'edge'],
          getContent(e) {
            const outDiv = document.createElement('div');
            const {item} = e;

            // 设置 div 的样式
            outDiv.style.display = 'flex';
            outDiv.style.justifyContent = 'center'; // 水平居中
            outDiv.style.alignItems = 'center';     // 垂直居中
            outDiv.style.width = '80px';
            outDiv.style.cursor = 'pointer';

            // 创建并设置内部 p 标签的样式
            const deleteNode = document.createElement('p');
            deleteNode.id = 'deleteNode';
            deleteNode.style.textAlign = 'center'; // 文本居中
            deleteNode.style.cursor = 'pointer';
            deleteNode.title = item._cfg.type;
            deleteNode.textContent = '删除节点';

            // 将 p 标签添加到 div 中
            outDiv.appendChild(deleteNode);

            return outDiv;
          },
          handleMenuClick(target, item) {
            const {id, title} = target

            if (id) {
              vm[id](item, title)
            }
          }
        })
        const minimap = new G6.Minimap({
          size: [250, 150]
        })
        let plugins = []
        if (this.openType === 'create' || this.openType === 'edit') {
          plugins = [menu, minimap, grid]
        } else {
          plugins = [minimap, grid]
        }
        const cfg = registerFactory(G6, {
          width: window.innerWidth,
          height: window.innerHeight,
          // renderer: 'svg',
          layout: {
            type: '' // 位置将固定
          },
          // 所有节点默认配置
          defaultNode: {
            type: 'rect-node',
            style: {
              radius: 10,
              width: 200,
              height: 50,
              cursor: 'move',
              fill: '#ecf3ff'
            },
            labelCfg: {
              fontSize: 20,
              style: {
                cursor: 'move',
                fontSize: 20
              }
            }
          },
          // 所有边的默认配置
          defaultEdge: {
            type: 'polyline-edge', // 扩展了内置边, 有边的事件
            style: {
              radius: 5,
              offset: 15,
              stroke: '#aab7c3',
              lineAppendWidth: 10, // 防止线太细没法点中
              endArrow: true
            }
          },
          // 覆盖全局样式
          nodeStateStyles: {
            'nodeState:default': {
              opacity: 1
            },
            'nodeState:hover': {
              opacity: 0.8
            },
            'nodeState:selected': {
              opacity: 0.9
            }
          },
          // 默认边不同状态下的样式集合
          edgeStateStyles: {
            'edgeState:default': {
              stroke: '#aab7c3'
            },
            'edgeState:selected': {
              stroke: '#1890FF'
            },
            'edgeState:hover': {
              animate: true,
              animationType: 'dash',
              stroke: '#1890FF'
            }
          },
          modes: {
            // 支持的 behavior
            default: ['drag-canvas', 'drag-shadow-node', 'canvas-event', 'delete-item', 'select-node', 'hover-node', 'active-edge', 'zoom-canvas'],
            originDrag: ['drag-canvas', 'drag-node', 'canvas-event', 'delete-item', 'select-node', 'hover-node', 'active-edge', 'zoom-canvas']
          },
          plugins: plugins
          // plugins: [menu, minimap, grid],
          // ... 其他G6原生入参
        })

        this.graph = new G6.Graph(cfg)
        // this.graph.read(data); // 读取数据
        this.restoreGraph(data)
        window.$welabxG6 = this.graph
        // this.graph.paint(); // 渲染到页面
        // this.graph.get('canvas').set('localRefresh', false); // 关闭局部渲染
        // this.graph.fitView();
      },
      // 初始化图事件
      initGraphEvent() {
        this.graph.on('drop', e => {
          // console.log(11);
          const {originalEvent} = e
          if (originalEvent.dataTransfer) {
            const transferData = originalEvent.dataTransfer.getData('dragComponent')

            if (transferData) {
              this.addNode(transferData, e)
            }
          }
        })

        this.graph.on('node:drop', e => {
          // console.log(22);
          e.item.getOutEdges().forEach(edge => {
            edge.clearStates('edgeState')
          })
          // this.refreshGraph();
        })

        this.graph.on('after-node-selected', e => {
          // console.log(33);
          if (this.openType === 'deploy') {
            if (e && e.item) {
              const model = e.item.get('model')
              if (model.dataType !== 'yaml') {
                this.$refs.serviceGroupDeployDrawer.configVisible = !!e
                this.selectAppName = model.data.appName
                this.selectAppInterface = model.data.appInterface
                let filter = this.gvStoreGroupDeployVo.nodes.filter(ele => ele.appName === model.data.appName);
                if (filter.length > 0) {
                  this.$refs.serviceGroupDeployDrawer.appVersion = filter[0].appVersion;
                  this.$refs.serviceGroupDeployDrawer.gvStoreYamlDeployVo = filter[0].yamlDeploy;
                } else {
                  this.$refs.serviceGroupDeployDrawer.appVersion = "";
                }
              } else {
                this.$refs.serviceGroupYamlDeployDrawer.configVisible = !!e
                this.selectYamlId = model.data.id;
                this.selectYamlAppName = model.data.appName;
                this.selectYamlInterface = model.data.yamlInterface;
                let filter = this.gvStoreGroupDeployVo.nodes.filter(ele => ele.appName === model.data.appName);
                if (filter.length > 0) {
                  if (filter[0].appType === 1 && filter[0].deployType === 0) {
                    this.$refs.serviceGroupYamlDeployDrawer.gvYamlCloudDeploy = filter[0].yamlCloudDeploy;
                    this.$refs.serviceGroupYamlDeployDrawer.value1 = true;
                  } else {
                    this.$refs.serviceGroupYamlDeployDrawer.value1 = false;
                    this.$refs.serviceGroupYamlDeployDrawer.currentSelectedId = filter[0].deployId;
                    this.$refs.serviceGroupYamlDeployDrawer.fetchGetData(this.selectYamlId, this.selectYamlAppName, this.selectYamlInterface);
                  }
                } else {
                  this.$refs.serviceGroupYamlDeployDrawer.value1 = true;
                  this.$refs.serviceGroupYamlDeployDrawer.getYamlInfoById(this.selectYamlId);
                  // this.$refs.serviceGroupYamlDeployDrawer.gvYamlCloudDeploy = {};
                }
              }
              this.config = model
              this.label = model.label
              this.labelCfg = {
                fontSize: model.labelCfg.fontSize,
                style: {
                  fill: model.labelCfg.style.fill
                }
              }
              this.node = {
                fill: model.style.fill,
                borderColor: model.style.stroke,
                lineDash: model.style.lineDash || 'none',
                width: model.style.width,
                height: model.style.height,
                shape: model.type
              }
              this.$nextTick(() => {
                if (model.dataType !== 'yaml') {
                  if (this.$refs.serviceGroupDeployDrawer !== undefined) {
                    this.$refs.serviceGroupDeployDrawer.$on('addServiceGroupOneServiceToGvStoreGroupDeployVo',
                      this.addServiceGroupOneServiceToGvStoreGroupDeployVo
                    );
                    this.$refs.serviceGroupDeployDrawer.$on('addExistInstanceService',
                      this.addExistInstanceService, this.detailType
                    )
                  }
                } else {
                  if (this.$refs.serviceGroupYamlDeployDrawer !== undefined) {
                    this.$refs.serviceGroupYamlDeployDrawer.$on('addServiceGroupOneServiceByYaml',
                      this.addServiceGroupOneServiceByYaml
                    );
                    this.$refs.serviceGroupYamlDeployDrawer.$on('addServiceGroupInstanceByYaml',
                      this.addServiceGroupInstanceByYaml
                    );
                  }
                }
              })
            }
          }
        })

        this.graph.on('on-node-mouseenter', e => {
          // console.log(44);
          if (e && e.item) {
            e.item.getOutEdges().forEach(edge => {
              edge.clearStates('edgeState')
              edge.setState('edgeState', 'hover')
            })
          }
        })

        // 鼠标拖拽到画布外时特殊处理
        this.graph.on('mousedown', e => {
          // console.log(55);
          this.isMouseDown = true
        })
        this.graph.on('mouseup', e => {
          // console.log(66);
          this.isMouseDown = false
        })
        this.graph.on('canvas:mouseleave', e => {
          // console.log(77);
          this.graph.getNodes().forEach(x => {
            const group = x.getContainer()

            group.clearAnchor()
            x.clearStates('anchorActived')
          })
        })

        this.graph.on('on-node-mousemove', e => {
          // console.log(88);
          if (e && e.item) {
            // this.tooltip = e.item.get('model').id
            this.tooltip = e.item.get('model').data.appZhname + "\r\n 标识：" + e.item.get('model').data.appName
            this.left = e.clientX + 40
            this.top = e.clientY - 20
          }
        })

        this.graph.on('on-node-mouseleave', e => {
          // console.log(99);
          if (e && e.item) {
            // this.tooltip = e.item.get('model').id;
            this.tooltip = ''
            if (e && e.item) {
              e.item.getOutEdges().forEach(edge => {
                edge.clearStates('edgeState')
              })
            }
          }
        })

        this.graph.on('before-node-removed', ({target, callback}) => {
          setTimeout(() => {
            // 确认提示
            callback(true)
          }, 1000)
        })

        this.graph.on('after-node-dblclick', e => {
          // console.log(1010);
          if (e && e.item) {
            console.log(e.item)
          }
        })

        this.graph.on('after-edge-selected', e => {
          // this.configVisible = !!e;
          this.configVisible = false
          // console.log(1111);
          if (e && e.item) {
            this.config = e.item.get('model').id

            this.graph.updateItem(e.item, {
              // shape: 'line-edge',
              style: {
                radius: 10,
                lineWidth: 2
              }
            })
          }
        })

        this.graph.on('on-edge-mousemove', e => {
          // console.log(1212);
          if (e && e.item) {
            // this.tooltip = e.item.get('model').label;
            this.left = e.clientX + 40
            this.top = e.clientY - 20
          }
        })

        this.graph.on('on-edge-mouseleave', e => {
          // console.log(1313);
          if (e && e.item) {
            this.tooltip = ''
          }
        })

        this.graph.on('before-edge-add', ({source, target, sourceAnchor, targetAnchor}) => {
          // console.log(1414);
          setTimeout(() => {
            this.graph.addItem('edge', {
              id: `${+new Date() + (Math.random() * 10000).toFixed(0)}`, // edge id
              source: source.get('id'),
              target: target.get('id'),
              sourceAnchor,
              targetAnchor
              // type: 'cubic-edge',
              // label:  'edge label',
            })
            this.refreshGraph()
          }, 100)
        })
      },
      changeMode() {
        if (this.mode === 'drag-node') {
          this.mode = 'drag-shadow-node'
          this.graph.setMode('default')
        } else {
          this.mode = 'drag-node'
          this.graph.setMode('originDrag')
        }
      },
      deleteNode(item, type) {
        // if (type === 'node') {
        //   console.log('node');
        // } else if (type === 'edge') {
        //   console.log('edge');
        // }
        this.graph.removeItem(item)
        this.configVisible = false
        this.refreshGraph()
        this.$refs.itemPanelList.filterPackageList()
      },
      refreshGraph() {
        let save = this.graph.save()
        this.graph.read(save)
      },
      changeBackgroundColor(appName) {
        let save = this.graph.save()
        let filter = save.nodes.filter(ele => ele.data.appName === appName);
        if (filter.length > 0) {
          filter[0].style.fill = "#e6f8dd";
        }
        this.graph.read(save)
      },
      // 添加节点
      addNode(transferData, {x, y}) {
        const {label, shape, fill, data, dataType} = JSON.parse(transferData)
        let tmpLabelStr = ""
        if (label.length > 13) {
          tmpLabelStr = "名称：" + label.substring(0, 12) + "...\n标识："
        } else {
          tmpLabelStr = "名称：" + label + "\n标识："
        }
        if (data.appName.length > 13) {
          tmpLabelStr = tmpLabelStr + data.appName.substring(0, 12) + "..."
        } else {
          tmpLabelStr = tmpLabelStr + data.appName
        }
        const model = {
          label: tmpLabelStr,
          // label: "名称：" + label + "\n标识：" + data.appName,
          // id:  Util.uniqueId(),
          id: `${+new Date() + (Math.random() * 10000).toFixed(0)}`, // edge id
          // 形状
          type: shape,
          style: {
            fill: fill || '#ecf3ff',
          },
          labelCfg: {
            "fontSize": 20,
            "style": {
              "cursor": "move",
              "fontSize": 15,
            }
          },
          // 坐标
          x,
          y,
          data,
          dataType
        }
        this.graph.addItem('node', model)
        this.refreshGraph()
        this.$refs.itemPanelList.filterPackageList()
      },
      save() {
        if (this.graph.cfg.data.nodes === undefined) {
          this.$message.warning('请先选择数据')
          return
        }
        if (this.graph.cfg.data.nodes.length === 0) {
          this.$message.warning('请先选择数据')
          return
        }
        this.gvStoreGroupVo.appIdList = []
        let databaseModel = {
          nodes: [],
          edges: []
        }
        this.graph.cfg.data.nodes.forEach(ele => {
          let tmpNode = {}
          this.gvStoreGroupVo.appIdList.push(ele.data.id)
          tmpNode.id = ele.id
          tmpNode.x = ele.x
          tmpNode.y = ele.y
          tmpNode.data = ele.data
          tmpNode.dataType = ele.dataType
          databaseModel.nodes.push(tmpNode)
        })
        this.graph.cfg.data.edges.forEach(ele => {
          let tmpEdge = {}
          tmpEdge.id = ele.id
          tmpEdge.source = ele.source
          tmpEdge.target = ele.target
          tmpEdge.sourceAnchor = ele.sourceAnchor
          tmpEdge.startPoint = ele.startPoint
          tmpEdge.endPoint = ele.endPoint
          databaseModel.edges.push(tmpEdge)
        })
        this.gvStoreGroupVo.relationGraph = JSON.stringify(databaseModel)
        this.$appStoreApi.saveGroupInfo(this.gvStoreGroupVo).then((res) => {
          if (res && res.code === 200) {
            this.$message.success('保存服务组成功！')
            this.$router.push({
              name: 'ServiceGroup'
            })
          }
        })
      },
      restoreGraph(data) {
        if (data !== null) {
          let databaseModel = JSON.parse(data)
          let tmpData = {
            nodes: [],
            edges: []
          }
          databaseModel.nodes.forEach(ele => {
            let tmpNode = {}
            tmpNode.id = ele.id
            tmpNode.x = ele.x
            tmpNode.y = ele.y
            tmpNode.data = ele.data
            let tmpLabelStr = ""
            if (ele.data.appZhname.length > 13) {
              tmpLabelStr = "名称：" + ele.data.appZhname.substring(0, 12) + "...\n 标识："
            } else {
              tmpLabelStr = "名称：" + ele.data.appZhname + "\n 标识："
            }
            if (ele.data.appName.length > 13) {
              tmpLabelStr = tmpLabelStr + ele.data.appName.substring(0, 12) + "..."
            } else {
              tmpLabelStr = tmpLabelStr + ele.data.appName
            }
            // tmpNode.label = "名称：" + ele.data.appZhname + "\n 标识：" + ele.data.appName
            tmpNode.label = tmpLabelStr
            tmpNode.dataType = ele.dataType
            tmpNode.style = {
              'nodeState:default': {
                'opacity': 1
              },
              'nodeState:hover': {
                'opacity': 0.8
              },
              'nodeState:selected': {
                'opacity': 0.9
              },
              'radius': 10,
              'width': 200,
              'height': 50,
              'cursor': 'move',
              'fill': '#eef5fe'
            }
            tmpNode.labelCfg = {
              'fontSize': 20,
              'style': {
                'cursor': 'move',
                'fontSize': 15
              }
            }
            tmpNode.type = 'rect-node'
            tmpData.nodes.push(tmpNode)
          })
          databaseModel.edges.forEach(ele => {
            let tmpEdge = {}
            tmpEdge.id = ele.id
            tmpEdge.source = ele.source
            tmpEdge.target = ele.target
            tmpEdge.sourceAnchor = ele.sourceAnchor
            tmpEdge.startPoint = ele.startPoint
            tmpEdge.endPoint = ele.endPoint
            tmpEdge.type = 'polyline-edge'
            tmpEdge.style = {
              'edgeState:default': {
                'stroke': '#aab7c3',
                'lineWidth': 1
              },
              'edgeState:selected': {
                'stroke': '#1890FF'
              },
              'edgeState:hover': {
                'animate': true,
                'animationType': 'dash',
                'stroke': '#1890FF'
              },
              'radius': 5,
              'offset': 15,
              'stroke': '#aab7c3',
              'lineAppendWidth': 10,
              'endArrow': true
            }
            tmpData.edges.push(tmpEdge)
          })
          this.graph.read(tmpData)
        }
      },
      backToServiceGroup() {
        this.$router.push({
          name: 'ServiceGroup'
        })
      },
      zoomFn(num) {
        this.graph.zoom(num);
      },
      dumpImage() {
        this.graph.downloadFullImage(this.gvStoreGroupVo.groupName, 'image/png', {
          backgroundColor: '#ddd',
          padding: [30, 15, 15, 15],
        });
      },
      beforeBack() {
        this.serviceGroupInstance = this.$route.params.serviceGroupInfo
        this.gvStoreGroupVo.groupDescription = this.serviceGroupInstance.groupDescription
        this.gvStoreGroupVo.groupName = this.serviceGroupInstance.groupName
        this.$appStoreApi.getGroupRelationGraph(this.serviceGroupInstance.id).then((res) => {
          if (res && res.code === 200) {
            this.serviceGroupInstance.relationGraph = res.data
            this.$nextTick(() => {
              this.createGraphic(this.serviceGroupInstance.relationGraph)
              this.initGraphEvent()
            })
          }
        })
      },
      addServiceGroupOneServiceToGvStoreGroupDeployVo(oneServiceDetail) {
        const existingIndex = this.gvStoreGroupDeployVo.nodes.findIndex(
          (item) => item.appName === oneServiceDetail.yamlDeployBaseInfo.appName
        )
        this.nodeInfo.appName = oneServiceDetail.yamlDeployBaseInfo.appName
        this.nodeInfo.appVersion = oneServiceDetail.yamlDeployBaseInfo.version
        this.nodeInfo.appType = 0
        this.nodeInfo.deployType = 0
        this.nodeInfo.yamlDeploy = oneServiceDetail
        if (existingIndex !== -1) {
          // 如果已存在相同的 key，则更新对应的 value
          this.$set(this.gvStoreGroupDeployVo.nodes, existingIndex, {
            ...this.gvStoreGroupDeployVo.nodes[existingIndex],
            ...this.nodeInfo
          })
          this.$message.success('更新成功')
        } else {
          // 如果不存在相同的 key，则添加新的数据
          this.gvStoreGroupDeployVo.nodes.push({...this.nodeInfo})
          this.$message.success('保存成功')
        }
        this.changeBackgroundColor(this.nodeInfo.appName);
        this.$refs.serviceGroupDeployDrawer.beforeCloseDrawer(null)
        this.$refs.serviceGroupDeployDrawer.$off('addServiceGroupOneServiceToGvStoreGroupDeployVo')
        this.$refs.serviceGroupDeployDrawer.$off('addExistInstanceService')
        this.nodeInfo = {
          appType: '',
          deployType: '',
          deployId: '',
          appName: '',
          appVersion: '',
          depends: [],
          useAppliedDeploy: false,
          yamlDeploy: {},
          yamlCloudDeploy: {},
        };
      },
      addServiceGroupOneServiceByYaml(yamlCloudInfo) {
        const existingIndex = this.gvStoreGroupDeployVo.nodes.findIndex(
          (item) => item.appName === yamlCloudInfo.yamlName
        )
        this.nodeInfo.appName = yamlCloudInfo.yamlName
        this.nodeInfo.appVersion = yamlCloudInfo.yamlVersion
        this.nodeInfo.appType = 1
        this.nodeInfo.deployType = 0
        this.nodeInfo.yamlCloudDeploy = yamlCloudInfo
        if (existingIndex !== -1) {
          // 如果已存在相同的 key，则更新对应的 value
          this.$set(this.gvStoreGroupDeployVo.nodes, existingIndex, {
            ...this.gvStoreGroupDeployVo.nodes[existingIndex],
            ...this.nodeInfo
          })
          this.$message.success('更新成功')
        } else {
          // 如果不存在相同的 key，则添加新的数据
          this.gvStoreGroupDeployVo.nodes.push({...this.nodeInfo})
          this.$message.success('保存成功')
        }
        this.changeBackgroundColor(this.nodeInfo.appName);
        this.$refs.serviceGroupYamlDeployDrawer.beforeCloseDrawer(null)
        this.$refs.serviceGroupYamlDeployDrawer.$off('addServiceGroupOneServiceByYaml')
        this.$refs.serviceGroupYamlDeployDrawer.$off('addServiceGroupInstanceByYaml')
        this.nodeInfo = {
          appType: '',
          deployType: '',
          deployId: '',
          appName: '',
          appVersion: '',
          depends: [],
          useAppliedDeploy: false,
          yamlDeploy: {},
          yamlCloudDeploy: {},
        };
      },
      addExistInstanceService(serviceInstance, type) {
        const existingIndex = this.gvStoreGroupDeployVo.nodes.findIndex((item) => item.appName === serviceInstance.appName
        );
        if (type === "serviceDeploy") {
          this.nodeInfo.appType = 0;
          this.nodeInfo.deployType = 1;
          this.nodeInfo.deployId = serviceInstance.id;
          this.nodeInfo.appName = serviceInstance.appName;
          this.nodeInfo.appVersion = serviceInstance.appVersion;
        } else if (type === "outService") {
          this.nodeInfo.appType = 0;
          this.nodeInfo.deployType = 2;
          this.nodeInfo.deployId = serviceInstance.serviceId;
          this.nodeInfo.appName = serviceInstance.serviceName;
        }
        if (existingIndex !== -1) {
          // 如果已存在相同的 key，则更新对应的 value
          this.$set(this.gvStoreGroupDeployVo.nodes, existingIndex, {
            ...this.gvStoreGroupDeployVo.nodes[existingIndex],
            ...this.nodeInfo,
          });
          this.$message.success("更新成功");
        } else {
          // 如果不存在相同的 key，则添加新的数据
          this.gvStoreGroupDeployVo.nodes.push({...this.nodeInfo});
          this.$message.success("保存成功");
        }
        this.changeBackgroundColor(this.nodeInfo.appName);
        this.showExistInstanceDialogDiv = false;
        this.$refs.serviceGroupDeployDrawer.$off("addExistInstanceService");
        this.$refs.serviceGroupDeployDrawer.$off("addServiceGroupOneServiceToGvStoreGroupDeployVo");
        this.nodeInfo = {
          appType: '',
          deployType: '',
          deployId: '',
          appName: '',
          appVersion: '',
          depends: [],
          useAppliedDeploy: false,
          yamlDeploy: {},
          yamlCloudDeploy: {},
        };
      },
      addServiceGroupInstanceByYaml(serviceInstance, type) {
        console.log(serviceInstance);
        const existingIndex = this.gvStoreGroupDeployVo.nodes.findIndex((item) => item.appName === serviceInstance.appName);
        // if (serviceInstance.infoType === "cloudNativeInstance") {
        this.nodeInfo.appType = 1;
        if (serviceInstance.infoType === "cloudNativeInstance") {
          this.nodeInfo.deployType = 1;
        } else {
          this.nodeInfo.deployType = 2;
        }
        this.nodeInfo.deployId = serviceInstance.deployId;
        this.nodeInfo.appName = serviceInstance.appName;
        this.nodeInfo.appVersion = serviceInstance.appVersion;
        // } else if (type === "outService") {
        //   this.nodeInfo.infoType = serviceInstance.infoType;
        //   this.nodeInfo.deployId = serviceInstance.serviceId;
        //   this.nodeInfo.appName = serviceInstance.serviceName;
        // }
        if (existingIndex !== -1) {
          // 如果已存在相同的 key，则更新对应的 value
          this.$set(this.gvStoreGroupDeployVo.nodes, existingIndex, {
            ...this.gvStoreGroupDeployVo.nodes[existingIndex],
            ...this.nodeInfo,
          });
          this.$message.success("更新成功");
        } else {
          // 如果不存在相同的 key，则添加新的数据
          this.gvStoreGroupDeployVo.nodes.push({...this.nodeInfo});
          this.$message.success("保存成功");
        }
        this.changeBackgroundColor(this.nodeInfo.appName);
        this.$refs.serviceGroupYamlDeployDrawer.beforeCloseDrawer(null);
        this.$refs.serviceGroupYamlDeployDrawer.$off("addServiceGroupInstanceByYaml");
        this.$refs.serviceGroupYamlDeployDrawer.$off("addServiceGroupOneServiceByYaml");
        this.nodeInfo = {
          appType: '',
          deployType: '',
          deployId: '',
          appName: '',
          appVersion: '',
          depends: [],
          useAppliedDeploy: false,
          yamlDeploy: {},
          yamlCloudDeploy: {},
        };
      },
      deployServiceGroup() {
        const nodeListLength = this.graph.cfg.data.nodes.length
        if (this.gvStoreGroupDeployVo.nodes.length !== nodeListLength) {
          this.$message.warning('请将所有节点数据进行绑定后，再进行部署')
          return
        }
        this.graph.cfg.data.nodes.forEach((ele) => {
          let tmpNodeInfo = {
            appType: '',
            deployType: '',
            deployId: '',
            appName: '',
            appVersion: '',
            depends: [],
            useAppliedDeploy: false,
            yamlDeploy: {},
            yamlCloudDeploy: {},
          }
          tmpNodeInfo = this.gvStoreGroupDeployVo.nodes.filter((gvStore) => ele.data.appName === gvStore.appName)[0]
          let edgeForId = []
          edgeForId = this.graph.cfg.data.edges.filter(edge => edge.source === ele.id)
          if (edgeForId.length !== 0) {
            const tmpDeps = []
            edgeForId.forEach((ed) => {
              let filter = []
              filter = this.graph.cfg.data.nodes.filter(node => node.id === ed.target)
              filter.forEach((fil) => {
                const filter1 = this.gvStoreGroupDeployVo.nodes.filter((e) => e.appName === fil.data.appName)[0]
                const tmpDep = {
                  appName: filter1.appName,
                  appVersion: filter1.appVersion
                }
                tmpDeps.push(tmpDep)
              })
            })
            tmpNodeInfo.depends = tmpDeps
          }
          const existingIndex = this.gvStoreGroupDeployVo.nodes.findIndex((item) => item.appName === tmpNodeInfo.appName)
          if (existingIndex !== -1) {
            this.gvStoreGroupDeployVo.nodes[existingIndex] = Object.assign({},
              this.gvStoreGroupDeployVo.nodes[existingIndex], tmpNodeInfo)
          }
        })
        this.deployDialogVisible = true
      },
      openFullScreen2() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        return loading
      },

      startDeploy() {
        if (this.gvStoreGroupDeployVo.groupName === '') {
          this.$message.warning('请输入服务组实例名称')
          return
        }
        const result = this.openFullScreen2();
        this.gvStoreGroupDeployVo.groupId = this.serviceGroupInstance.id
        this.gvStoreGroupDeployVo.tenantId = getTenantId()
        this.gvStoreGroupDeployVo.relationGraph = this.serviceGroupInstance.relationGraph
        this.$appManageApi.createGroupDeploy(this.gvStoreGroupDeployVo).then((res) => {
          if (res && res.code === 200) {
            result.close();
            this.$message.success('服务组部署成功')
            this.clearDialogInfo()
            this.$router.push({
              name: 'ServiceGroupList'
            })
            this.$appManageApi.startGroupDeploy([res.data]).then((res) => {
              if (res && res.code === 200) {
                result.close();
                this.$message.success('服务组启动成功')
                this.clearDialogInfo()
                this.$router.push({
                  name: 'ServiceGroupList'
                })
              }
            }).catch((error) => {
              result.close();
              this.$message.error(error.message);
            });
          }
        }).catch((error) => {
          result.close();
          this.$message.error(error.message);
        }).finally(() => {
          result.close();
        });
      },
      clearDialogInfo() {
        this.gvStoreGroupDeployVo.groupName = ''
        this.deployDialogVisible = false
      }
    },
    // beforeMount() {
    //   if (this.$route.params.openType === undefined) {
    //     this.$router.push({
    //       name: 'ServiceGroup'
    //     })
    //     return
    //   }
    //   this.openType = this.$route.params.openType
    //   // if (this.$route.params.openType === "create") {
    //   //   this.gvStoreGroupVo.groupDescription = this.$route.params.serviceGroupDesc;
    //   //   this.gvStoreGroupVo.groupName = this.$route.params.serviceGroupIndicate;
    //   //   this.gvStoreGroupVo.groupZhname = this.$route.params.serviceGroupName;
    //   // } else if (this.$route.params.openType === "deploy") {
    //   //
    //   // } else if (this.$route.params.openType === "detail") {
    //   //   this.serviceGroupInstance = this.$route.params.serviceGroupInfo;
    //   // } else if (this.$route.params.openType === "edit") {
    //   //
    //   // }
    // },
    beforeMount() {
      if (this.$route.params.openType === undefined) {
        this.$router.push({
          name: 'ServiceGroup'
        })
        return
      }
      this.openType = this.$route.params.openType
      if (this.openType === 'create') {
        this.marginLeftSize = "300px";
        this.gvStoreGroupVo.groupDescription = this.$route.params.serviceGroupDesc
        this.gvStoreGroupVo.groupName = this.$route.params.serviceGroupName
        // this.gvStoreGroupVo.groupZhname = this.$route.params.serviceGroupName
        this.$nextTick(() => {
          this.createGraphic(null)
          this.initGraphEvent()
        })
      } else if (this.openType === 'deploy') {
        this.serviceGroupInstance = this.$route.params.serviceGroupInfo
        this.marginLeftSize = "10px";
        this.$appStoreApi.getGroupRelationGraph(this.serviceGroupInstance.id).then((res) => {
          if (res && res.code === 200) {
            // this.serviceGroupInstance.relationGraph = res.data
            let parse = JSON.parse(res.data);
            parse.nodes.forEach(node => {
              node.x = node.x - 300;
            })
            this.serviceGroupInstance.relationGraph = JSON.stringify(parse);
            // 创建画布
            this.$nextTick(() => {
              this.createGraphic(this.serviceGroupInstance.relationGraph)
              this.initGraphEvent()
            })
          }
        })
      } else if (this.openType === 'detail') {
        this.serviceGroupInstance = this.$route.params.serviceGroupInfo
        this.marginLeftSize = "10px";
        this.$appStoreApi.getGroupRelationGraph(this.serviceGroupInstance.id).then((res) => {
          if (res && res.code === 200) {
            // this.serviceGroupInstance.relationGraph = res.data
            let parse = JSON.parse(res.data);
            parse.nodes.forEach(node => {
              node.x = node.x - 300;
            })
            this.serviceGroupInstance.relationGraph = JSON.stringify(parse);
            this.$nextTick(() => {
              this.createGraphic(this.serviceGroupInstance.relationGraph)
              // this.initGraphEvent();
            })
          }
        })
      } else if (this.openType === 'edit') {
        this.marginLeftSize = "300px";
        this.serviceGroupInstance = this.$route.params.serviceGroupInfo
        this.gvStoreGroupVo.groupDescription = this.serviceGroupInstance.groupDescription
        this.gvStoreGroupVo.groupName = this.serviceGroupInstance.groupName
        // this.gvStoreGroupVo.groupZhname = this.serviceGroupInstance.groupZhname
        this.$appStoreApi.getGroupRelationGraph(this.serviceGroupInstance.id).then((res) => {
          if (res && res.code === 200) {
            this.serviceGroupInstance.relationGraph = res.data
            this.$nextTick(() => {
              this.createGraphic(this.serviceGroupInstance.relationGraph)
              this.initGraphEvent()
            })
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  /* 提示框的样式 */
  .g6-tooltip {
    position: fixed;
    top: 0;
    left: 0;
    font-size: 12px;
    color: #545454;
    border-radius: 4px;
    border: 1px solid #e2e2e2;
    background-color: rgba(255, 255, 255, 0.9);
    box-shadow: rgb(174, 174, 174) 0 0 10px;
    padding: 10px 8px;
  }

  .g6-minimap {
    position: absolute;
    right: 0;
    bottom: 0;
    background: #fff;
  }

  /* 新增各二级菜单全局样式布局 */
  .global-container1 {
    /* background-image: url(../../assets/back_images/background.png);  */
    background-size: cover;
    /* width: 98%; */
    /* margin-left: 1%; */
    padding: 20px;
    height: 92vh;
    display: flex;
    flex-direction: column;
    margin-bottom: 10px;
  }
</style>
